package pl.edu.agh.pros.proxy.logic.dao.register;

import java.util.Collection;

import pl.edu.agh.pros.conf.RegistrationConstants;
import pl.edu.agh.pros.proxy.logic.dao.AppConfigurationDAO;
import pl.edu.agh.pros.proxy.logic.dao.common.AbstractDAO;
import pl.edu.agh.pros.proxy.model.AppConfiguration;
import pl.edu.agh.pros.proxy.model.RegisteredTopic;

public class RegisteredTopicDAO extends AbstractDAO<RegisteredTopic> {

	private static final RegisteredTopicDAO instance = new RegisteredTopicDAO();

	private RegisteredTopicDAO() {
		super(RegisteredTopic.class);
	}

	public static RegisteredTopicDAO getInstance() {
		return instance;
	}

	public Long registerTopic(String appKey, String topicName, String roomName) {
		AppConfiguration appCfg = AppConfigurationDAO.getInstance().getObject("providerAppKey==param1",
				"String param1", appKey);
		if (appCfg == null) {
			return null;
		}

		RegisteredTopic registeredTopic = this.getObject("appKey==param1 && topicName==param2",
				"String param1, String param2", appKey, topicName);
		if (registeredTopic == null) {
			registeredTopic = new RegisteredTopic();
			registeredTopic.setAppKey(appKey);
			registeredTopic.setTopicName(topicName);
		}
		registeredTopic.setRoomName(roomName);
		registeredTopic.setRegistrationTime(System.currentTimeMillis());
		this.save(registeredTopic);
		return RegistrationConstants.TOPIC_REGISTRATION_DURATION;
	}

	public String getTopicRoomName(String appKey, String topicName) {
		AppConfiguration appCfg = AppConfigurationDAO.getInstance().getObject("clientAppKey==param1", "String param1",
				appKey);
		if (appCfg == null) {
			appCfg = AppConfigurationDAO.getInstance().getObject("providerAppKey==param1", "String param1", appKey);
			if (appCfg == null) {
				return null;
			}
		}

		RegisteredTopic registeredTopic = this.getObject("appKey==param1 && topicName==param2",
				"String param1, String param2", appCfg.getProviderAppKey(), topicName);
		if (registeredTopic == null) {
			return null;
		} else {
			return registeredTopic.getRoomName();
		}
	}

	public void clearExpiredTopics() {
		Collection<RegisteredTopic> expiredTopics = this.getObjects("registrationTime < param1", "Long param1",
				System.currentTimeMillis() - RegistrationConstants.TOPIC_REGISTRATION_DURATION);
		this.deleteAll(expiredTopics);
	}
}